// import { readWorkbookFromRemoteFile, } from "./file";
import {
    minioAddress,
    minioPort,
    minioServer,
    minioBucket,
} from "@/views/device/devicegroups/uploadImg";
// import * as FileSaver from 'file-saver'; //打印
import _ from 'lodash'
import { Message } from 'element-ui'
import { generateId } from "@/utils/index";
// let Minio = require("minio");
// let stream = require("stream");
import Vue from 'vue'
// export async function useExecl(url, parameter, fileName, technologyParameterLength, deviceInfoList) {
//     return new Promise(async (resolve, reject) => {
//         readWorkbookFromRemoteFile(url, parameter, technologyParameterLength, deviceInfoList, async (workbook) => {
//             try {
//                 const buffer = await workbook.xlsx.writeBuffer();
//                 // console.log('fileSaver :>> ', FileSaver);
//                 const res = await putObject(buffer, fileName)
//                 resolve(res)
//             } catch (error) {
//                 reject()
//             }


//         });
//     })


// }
function editExecl() {

}
function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
}
async function putObject(sheetfile, SheetNames) {

    const minioClient = new Vue.prototype.$Minio.Client(minioServer);
    return new Promise(async (resolve, reject) => {
        // var wopts = {
        //     bookType: "xlsx", // 要生成的文件类型
        //     bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        //     type: "binary",
        // };

        // return
        // const buffer = await sheetfile.xlsx.writeBuffer();
        // var wbout = XLSX.write(sheetfile, wopts);

        var blob = new Blob([sheetfile], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
        });
        // FileSaver.saveAs(blob, 'download.xlsx');
        // console.log(blob, "---------");
        // return;
        var file = new File([blob], SheetNames, {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",

            lastModified: Date.now(),
        });
        try {
            let fr = new FileReader(); //用FileReader 读取文件流
            fr.readAsArrayBuffer(file);

            fr.addEventListener("loadend", (e) => {
                const dataurl = e.target.result;
                let bufferStream = new Vue.prototype.$stream.PassThrough();
                //将buffer写入
                bufferStream.end(new Buffer(dataurl));
                //e.target.result 就是读取到的文件流 将其转为Buffer类型即可
                //上传
                //参数
                let metadata = {
                    "content-type": file.type,
                    "content-length": file.size,
                };

                minioClient.putObject(
                    minioBucket,
                    SheetNames,
                    bufferStream,
                    file.size,
                    metadata,
                    function (err, etag) {
                        if (err) {
                            Vue.prototype.$msg({
                                type: "warning",
                                message: "上传失败!",
                            });
                            reject()
                        } else {
                            const url = SheetNames

                            Vue.prototype.$msg({
                                type: "success",
                                message: "上传成功",
                            });
                            console.log('上传成功=>>>', url)
                            resolve(url)
                        }
                    }
                );
            });
        } catch (error) {
            console.log(error, 'error')
            reject()
        }

    });
}
// 取出树形结构最后一级
export function forxh(list, lastchildren) {
    const cloneList = _.cloneDeep(list)
    for (var i = 0; i < cloneList.length; i++) {
        var chlist = cloneList[i];
        // console.log(chlist);
        if (chlist.children) {
            forxh(chlist.children, lastchildren);
        } else {
            lastchildren.push(chlist.id);
        }
    }
    // return lastchildren
}
// 去重赋值 转树结构
// arr[i].deviceToken =
// arr[i].deviceInfoList[0].deviceList.join("、");
// arr[i].deviceTypeName =
// arr[i].deviceInfoList[0].deviceTypeName;
export function uniqueTree(res, key) {
    let arr = _.cloneDeep(res)
    var hash = [];
    for (var i = 0; i < arr.length; i++) {
        // 找到重复元素的下标
        const index = hash.findIndex(
            (findItem) => findItem[key] == arr[i][key]
        );
        // 不存在 添加 第一次循环 hash是空数组
        if (index == -1) {
            // 第一次添加的时候 添加一个children空数组 后续相同项添加到children内
            // arr[i].children = [];

            hash.push({
                ...arr[i],
            });
        } else {
            // 存在往当前下边的hash下 push
            hash[index].children.push({
                ...arr[i],
                id: generateId(),
                type: 2, //添加第二级标识
            });
        }
    }

    return hash;
}
export function setDevInfolist(res) {
    let cloneData = _.cloneDeep(res)
    cloneData.forEach((item) => {
        // item.deviceInfoList.push({
        //     deviceList: ['测试'],
        //     deviceTypeName: 'test'
        // })

        item.deviceInfoList.forEach((dev) => {
            dev.deviceList = dev.deviceList.map(m => m.deviceName).join('、');
        });


        // 取出第一级
        if (
            item.deviceInfoList.length !== 0 &&
            item.deviceInfoList.length > 1
        ) {
            item.deviceList = item.deviceInfoList[0].deviceList;
            item.deviceTypeName = item.deviceInfoList[0].deviceTypeName;
        }
        // 剩下的添加到第二级
        // if (item.deviceInfoList.length &&
        //     item.deviceInfoList.length == 1) {
        //     item.deviceInfoList[0].isDevice = false
        //     item.deviceInfoList[0].isDevLine = false

        // }
        if (item.deviceInfoList.length) {
            item.deviceInfoList[item.deviceInfoList.length - 1].isDevLine = item.deviceInfoList.length == 2 ? false : true
            for (let i = 0; i < item.deviceInfoList.length; i++) {
                let element = item.deviceInfoList[i];
                if (i == 0) {
                    item.deviceList = element.deviceList;
                    item.deviceTypeName = element.deviceTypeName;
                } else {
                    item.children.push({
                        version: item.version,
                        state: item.state,
                        createdDate: item.createdDate,
                        startDate: item.startDate,
                        endDate: item.endDate,
                        author: item.author,
                        // token: item.token,
                        ...element,
                        id: generateId(),
                        pid: item.id,
                        type: 2, //添加第二级标识
                        isDevice: item.deviceInfoList.length == 2 ? false : true,//设备
                        typeLine2: true
                    });
                }

            }
        }
    });
    return cloneData
}